package com.atues.backtrack.subsetWithDup;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path =  new ArrayList<>();
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        int[] used = new int[nums.length];

        backtracking(nums,0,used);

        return res;

    }

    void backtracking(int[] nums , int start,int[] used){
        res.add(new ArrayList<>(path));

        for(int i = start ; i < nums.length ; i++){
            if(i > 0 && nums[i] == nums[i-1] && used[i-1] == 0)continue;
            path.add(nums[i]);
            used[i] = 1;
            backtracking(nums,i+1,used);
            path.remove(path.size() - 1);
            used[i] = 0;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {1, 2, 2};
        List<List<Integer>> lists = solution.subsetsWithDup(nums);
        System.out.println(JSON.toJSONString(lists));
    }
}
